//
//  ViewController.swift
//  test
//
//  Created by zoushaoshao on 2018/11/28.
//  Copyright © 2018 TT. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    // 创建游戏对象
   lazy var game = Concentration(numberOfPairsOfCard: (cardButtons.count))
    
    var flipCount = 0{
        
        didSet{
            // 属性值观察
            flipsCountLabel.text = "Flips: \(flipCount)" // 反斜杠写法
        }
    }
    
    @IBOutlet var cardButtons: [UIButton]! // 存放所有卡片按钮
    
    @IBOutlet weak var flipsCountLabel: UILabel! // 提示点击次数
    
    @IBOutlet weak var cardButton: UIButton! // 卡片按钮
    
    // 翻卡片
    @IBAction func FlipCard(_ sender: UIButton) {
        
        if let cardNumber = cardButtons.index(of : sender){
            
           game.chooseCard(cardIndex: cardNumber)
            updateViewFromModel()
        }
    }
    
    // when model changed ,update view
    func updateViewFromModel() {
        
        flipCount += 1

        for cardIndex in cardButtons.indices {
            
            if game.cards[cardIndex].isFaceUp{
                cardButtons[cardIndex].setTitle(emoji(card: game.cards[cardIndex]), for: .normal)
                cardButtons[cardIndex].backgroundColor =  #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
            }else{
                
                cardButtons[cardIndex].setTitle("", for: .normal)
                cardButtons[cardIndex].backgroundColor = game.cards[cardIndex].isMatched ? #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0) : #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
                
            }

        }
        
    }
    
    var emojiChoices = ["🦇","🐶","🦊","🐵","🦄","🐝","🐷","🦋"]

    var emojiDic = [Int:String]()
    
    func emoji(card : Card) -> String {
        
        if emojiDic[card.identifier] == nil, emojiChoices.count > 0 {
            let random = (Int)(arc4random_uniform(uint(emojiChoices.count)))
            emojiDic[card.identifier] = emojiChoices.remove(at: random)
            
        }
        return emojiDic[card.identifier] ?? "?"
    }
    
    
    func flipCard(withEmoji emoji:String,on sender:UIButton) {
        
        flipCount += 1

        if sender.currentTitle == emoji {
            
            sender.setTitle("", for: .normal)
            sender.backgroundColor = #colorLiteral(red: 1, green: 0.5763723254, blue: 0, alpha: 1)
            
        }else{
            
            sender.setTitle(emoji, for: .normal)
            sender.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
            
        }
        
        
        
    }
    

}

